package org.kia.commons;

import android.util.Log;

import java.lang.reflect.Type;

/**
 * Utilities for Class related methods
 *
 * @author Amir Lazarovich
 */
public final class ClassUtil {

    // Constants
    private static final String TAG = "ClassUtil";

    // Statics

    @SuppressWarnings("unchecked")
    public static <T> Class<T> castClass(Class<?> aClass) {
        return (Class<T>) aClass;
    }

    /**
     * Cast obj to provided class
     *
     * @param obj
     * @param targetClass
     * @param <T>
     * @return obj casted to given class or null if it is null or not an instance of T
     */
    public static <T> T cast(Object obj, Class<T> targetClass) {
        if (targetClass.isInstance(obj)) { // TODO check isAssignableFrom
            return targetClass.cast(obj);
        }

        return null;
    }

    /**
     * Get the class that represent this type
     *
     * @param targetClassType
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> Class<T> getClass(Type targetClassType) {
        Class<T> targetClass = null;
        String strippedDownType = targetClassType.toString().replaceAll("<.*>", "");
        try {
            targetClass = (Class<T>) Class.forName(strippedDownType);
        } catch (ClassNotFoundException e) {
             Log.e(TAG, "Trying to cast incompatible Type to its representative class", e);
        }

        return targetClass;
    }
}
